﻿using GodSharp;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ZK.Common;
using ZK.InterfaceServer;

namespace ZK.HardWareBLL
{
    /// <summary>
    /// 泥人232串口服务器 默认端口12345
    /// </summary>
    public class NRCOMServerBLL : BaseBLL
    {
        private readonly GodSerialPort _serialPort;
        private bool _isOpened;
        public int lightStatus = 0;
        public bool IsInit = false;
        public NRCOMServerBLL()
        {

        }

        public NRCOMServerBLL(Models.TerminalM terminalM)
        {
            try
            {
                this.IsInit = true;
                this.terminal = terminalM;
                Task.Factory.StartNew(() => {
                    try
                    {
                        lightStatus = 1;
                        ///创建客户端
                        var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
                        ///IP地址
                        IPAddress ip = IPAddress.Parse(this.terminal.ip);
                        ///端口号
                        IPEndPoint endPoint = new IPEndPoint(ip, (int)this.terminal.port);
                        ///建立与服务器的远程连接
                        client.Connect(endPoint);
                        ///线程问题
                        //Thread thread = new Thread(ReciveMsg);
                        //thread.IsBackground = true;
                        //thread.Start(client);
                        //将字符串指令转换为byte数组
                        // byte[] buf = System.Text.Encoding.Default.GetBytes("AT+STACH" + num + "=1,1\r\n");


                        while (true)
                        {
                            byte[] bytes = new byte[128];//真正使用时，接收缓冲区需要适当的调整
                                                           //等待硬件响应命令，接收到的数据为byte数组
                                                           //会等待到有数据返回为止
                            int recLen = client.Receive(bytes);
                            Common.Log4.LogManage.WriteInfo(string.Join("-", bytes));
                            byte[] bbz = null;
                            for (int i = 0; i < bytes.Length; i++)
                            {
                                if (bytes[i] == 2)
                                {
                                    bbz = bytes.Skip(i).Take(12).ToArray();
                                    goto A;
                                }
                            }
                        A:
                            if (bbz != null)
                            {
                                //nowWeight = weight;
                             
                                    DelegateHelper.NRA9Event?.Invoke(GetWeight(bbz));
                                
                               
                                //decimal weight = GetWeight(bbz);
                                //if ((weight != nowWeight) && (weight != -1))
                                //{
                                //    nowWeight = weight;
                                //    DelegateHelper.A9Event?.Invoke(GetWeight(bbz));
                                //}
                            }
                        }
                        client.Close();
                        //将byte数组转为字符串
                        // string str = System.Text.Encoding.Default.GetString(recbuf);
                    }
                    catch (Exception ex)
                    {
                        Common.Log4.LogManage.WriteErr(ex.ToString());
                    }
                }).Wait(3000);
            }
            catch (Exception ex)
            {
               // WebApiServer.AddHardWareLog(terminalM.name, ex.Message, "网络连接失败");
                Common.Log4.LogManage.WriteErr("红绿灯初始化 " + ex.ToString() + " 红绿灯信息 串口号：" + terminalM.com);
            }
        }

        private decimal GetWeight(byte[] bytes)
        {
            // Common.Log4.LogManage.WriteInfo(string.Join("-", bytes));
            if (bytes.Length == 12 && (bytes[0] == 2) && (bytes[11] == 3))
            {
                var number = 0;
                number += (bytes[2] - 48) * 100000;
                number += (bytes[3] - 48) * 10000;
                number += (bytes[4] - 48) * 1000;
                number += (bytes[5] - 48) * 100;
                number += (bytes[6] - 48) * 10;
                number += (bytes[7] - 48);
                return (decimal)number / 100;
                //return number;
            }
            else
            {
                //Common.Log4.LogManage.WriteErr("获取地磅数据长度有误 errDate:" + string.Join("-", bytes));
                return -1;
            }
        }

        public void Close()
        {
            _isOpened = !_serialPort.Close();
        }

     
    }
}
